//
//  YZMAccountViewController.m
//  YZMicroStock
//
//  Created by wangminhong on 16/3/23.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMAccountViewController.h"
#import "NSNumber+Utils.h"
#import <MJRefresh.h>
#import "YZClient+Account.h"
#import "YZGeneralResultModel.h"
#import "YZMSeparatorCell.h"
#import "YZMAlertView.h"
#import "YZClient+BankCard.h"
#import "YZMWebViewService.h"
#import "YZMDelayCharge.h"

#define HEADERHEIGHT self.view.bounds.size.height / 2
#define CELLHEIGHT 46
#define SECTIONFOOTER 1

static const int loginbefore = 101;
static const int loginafter = loginbefore + 1;

@interface YZMAccountViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) NSArray *dataArray;

@end

@implementation YZMAccountViewController {
    
    UITableView *_tableView;
    UIImageView *_headerView;
    UILabel *_balanceValueLabel;
    UIButton *_regButton;
    UIButton *_loginButton;
    MJRefreshNormalHeader *_refreshHeader;
}

- (id)init {
    
    if (self = [super init]) {
        
        self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
        if (YZMSWitchOn) {
            self.navigationItem.leftBarButtonItem = [YZMAppStyle leftBarItemWithImage:@"customer_service" target:self action:@selector(leftBarItemMethod)];
        }
        self.navigationItem.rightBarButtonItem = [YZMAppStyle rightBarItemWithImage:@"set" target:self action:@selector(rightBarItemMethod)];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushDraw:) name:@"pushdraw" object:nil];
    }
    
    return self;
}


- (NSArray *)dataArray {
    
    if (!_dataArray) {
        
        _dataArray = @[
                       @[@{@"titleName" : @"我的策略组", @"imageName" : @"mytack", YZNEXTPAGE : @"mytack"},
                         @{@"titleName" : @"停牌策略", @"imageName" : @"stoptack", YZNEXTPAGE : @"stoptack"}],
                       @[@{@"titleName" : @"资金明细", @"imageName" : @"fundDetail", YZNEXTPAGE : @"fundDetail"}]];
        
#ifdef YZMicroStock
        
        _dataArray = @[
                       @[@{@"titleName" : @"我的策略组", @"imageName" : @"mytack", YZNEXTPAGE : @"mytack"},
                         @{@"titleName" : @"停牌策略", @"imageName" : @"stoptack", YZNEXTPAGE : @"stoptack"}],
                       @[@{@"titleName" : @"资金明细", @"imageName" : @"fundDetail", YZNEXTPAGE : @"fundDetail"},
                         @{@"titleName" : @"我的红包", @"imageName" : @"myRedPacket", YZNEXTPAGE : @"RedPacket"},
                         @{@"titleName" : @"关注微信", @"imageName" : @"icon_weichat", YZNEXTPAGE : @"AboutWeichat"}]];
#endif

    }
    
    return _dataArray;
}


- (void)pushDraw:(NSNotification *)noti{
    [YZMCMInstance pushViewControllerWithName:@"draw" andParams:nil];
}


- (void)leftBarItemMethod {
    
    [YZMWebViewService openSuggestionCenter];
}

- (void)rightBarItemMethod {

    [YZMCMInstance pushByCheckingAuthWithName:@"accountDetail" andParams:nil];
}

- (void)contentRefesh {
    
    if (YZMUserServiceInstance.currentUser) {
        
        self.navigationItem.title = YZMUserServiceInstance.currentUser.username;
        
        [_regButton setTitle:@"充值" forState:UIControlStateNormal];
        _regButton.backgroundColor = [YZMAppStyle buttonSelectedColor];
        _regButton.layer.borderWidth = 0;
        [_regButton setTitleColor:[YZMAppStyle colorForMain] forState:UIControlStateNormal];
        _regButton.tag = loginafter;
        
        [_loginButton setTitle:@"提现" forState:UIControlStateNormal];
        _loginButton.backgroundColor = [YZMAppStyle buttonSelectedColor];
        _loginButton.layer.borderWidth = 0;
        [_loginButton setTitleColor:[YZMAppStyle colorForMain] forState:UIControlStateNormal];
        _loginButton.tag = loginafter;
        
        _tableView.mj_header = _refreshHeader;
    } else {
        
        self.navigationItem.title = @"未登录";
        
        _balanceValueLabel.text = @"0.00";
        
        [_regButton setTitle:@"注册" forState:UIControlStateNormal];
#ifdef YZMicroStock
        _regButton.backgroundColor = [UIColor clearColor];
        _regButton.layer.borderWidth = 1;
#else
        _regButton.backgroundColor = [YZMAppStyle colorForBarBGColor];
        _regButton.layer.borderWidth = 0;
#endif
        
        [_regButton setTitleColor:[YZMAppStyle colorForWhite] forState:UIControlStateNormal];
        
        _regButton.tag = loginbefore;
        
        [_loginButton setTitle:@"登录" forState:UIControlStateNormal];
#ifdef YZMicroStock
        _loginButton.backgroundColor = [UIColor clearColor];
        _loginButton.layer.borderWidth = 1;
#else
        _loginButton.backgroundColor = [YZMAppStyle colorForBarBGColor];
        _loginButton.layer.borderWidth = 0;
#endif
        
        [_loginButton setTitleColor:[YZMAppStyle colorForWhite] forState:UIControlStateNormal];
        _loginButton.tag = loginbefore;
        
        _tableView.mj_header = nil;
    }
    
}

- (void)balanceRefresh {
    
    _balanceValueLabel.text = @(YZMUserServiceInstance.user.assets.balance).decimalr02fString;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (YZMUserServiceInstance.isValidate) {
        [YZMUserServiceInstance fetchUserAssetsInfo];
    }
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
#ifdef YZMicroStock
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"icon_transparency_bg"] forBarMetrics:UIBarMetricsDefault];
#endif
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setBackgroundImage:[YZMAppStyle barBackgroundImage] forBarMetrics:UIBarMetricsDefault];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    //创建页面
    [self createObjects];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contentRefesh) name:YZMLoginSuccessNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(balanceRefresh) name:YZMUserAssetsUpdateNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contentRefesh) name:YZMLogoutSuccessNotification object:nil];
    
}

//- (void)viewDidDisappear:(BOOL)animated{
//    [super viewDidDisappear:animated];
//     [self.navigationController.navigationBar setBackgroundImage:[YZMAppStyle barBackgroundImage] forBarMetrics:UIBarMetricsDefault];
//}

#pragma mark -- createTableView

- (void)createObjects {
    
    WS(ws)
    _tableView = [[UITableView alloc] init];
    _tableView.backgroundColor = [YZMAppStyle appBackgroundColor];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//    [_tableView registerClass:[YZMSeparatorCell class] forCellReuseIdentifier:@"identifier"];
    
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        if (iPhoneX) {
            make.top.equalTo(ws.view).offset(-88);
        }else{
            make.top.equalTo(ws.view).offset(-64);
        }
        make.left.right.bottom.equalTo(ws.view);
    }];
    
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self createHeaderView];
    _tableView.tableHeaderView = _headerView;
    _tableView.tableFooterView = [[UIView alloc] init];
    _refreshHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(fetchUserInfo)];
}

- (void)createHeaderView {
    
    _headerView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, HEADERHEIGHT)];
    [_headerView setImage:[UIImage imageNamed:@"mybackground"]];

    UIView *backview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, HEADERHEIGHT)];
    backview.backgroundColor=[YZMAppStyle appBackgroundColor];
    
    if (YZMSWitchOn) {
        backview.alpha=0.8;
    }else{
#ifndef YZMicroStock
        backview.backgroundColor = [YZMAppStyle colorForWhite];
#endif
        backview.alpha = 1;
    }
    
    [_headerView addSubview:backview];
    _headerView.userInteractionEnabled=YES;
    [self headerContext];
}

- (void)headerContext {
    
    UIView *centerShow = [[UIView alloc] init];
    centerShow.backgroundColor = [UIColor yellowColor];
    [_headerView addSubview:centerShow];
    [centerShow mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(_headerView);
        make.centerY.equalTo(_headerView).with.offset(- 44 - 15 - 10);
    }];
    
    UILabel *balanceLabel = [YZMAppStyle labelWithWhite];
    balanceLabel.text = @"账户余额";
    [centerShow addSubview:balanceLabel];
    [balanceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        if (iPhone4 || iPhone5 || !(iPhone6 || iPhone6P)) {
            
            make.top.equalTo(centerShow).offset(25);
        } else {
            
            make.top.equalTo(centerShow);
        }
        make.centerX.equalTo(centerShow);
        make.height.mas_equalTo(20);
    }];
    _balanceValueLabel = [YZMAppStyle labelWithGigWhite];
    _balanceValueLabel.adjustsFontSizeToFitWidth = YES;
    _balanceValueLabel.minimumScaleFactor = 0.5;
    _balanceValueLabel.textAlignment = NSTextAlignmentCenter;
    [centerShow addSubview:_balanceValueLabel];
    [_balanceValueLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(balanceLabel.mas_bottom).with.offset(ControlSpacing15);
        make.centerX.equalTo(centerShow);
        make.height.mas_equalTo(40);
        make.width.mas_equalTo(ScreenWidth - 30);
    }];
    
    _regButton = [YZMAppStyle regButton];
    [_regButton addTarget:self action:@selector(registerAccount:) forControlEvents:UIControlEventTouchUpInside];
    [_headerView addSubview:_regButton];
    [_regButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(_headerView.mas_bottom).with.offset(-ControlSpacing15);
        make.left.equalTo(_headerView.mas_left).with.offset(ControlSpacing20);
        make.width.mas_equalTo(_headerView.bounds.size.width / 2 - 35);
        make.height.mas_equalTo(InputViewHeight);
    }];
    
    _loginButton = [YZMAppStyle regButton];
    [_loginButton addTarget:self action:@selector(loginAccount:) forControlEvents:UIControlEventTouchUpInside];
    [_headerView addSubview:_loginButton];
    [_loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(_headerView.mas_right).with.offset(-ControlSpacing20);
        make.bottom.and.width.height.equalTo(_regButton);
    }];
    
    [self contentRefesh];
    if (YZMUserServiceInstance.currentUser) {
        [self balanceRefresh];
    }

    
}

- (void)registerAccount:(UIButton *)send {
    
    if (send.tag == loginbefore) {
        
        [YZMHCMInstance pushViewControllerWithName:@"register" andParams:@{YZSOURCEPAGE:@"mine"}];
    } else {
        
        [YZMHCMInstance pushViewControllerWithName:@"recharge" andParams:nil];
    }

}

- (void)loginAccount:(UIButton *)send {
    if (send.tag == loginbefore) {
        [YZMHCMInstance pushViewControllerWithName:@"login" andParams:@{YZSOURCEPAGE:@"mine"}];
    } else {
            //检查是否已实名认证
        if (!YZMUserServiceInstance.user.detail.isNamed) {
            
            YZMAlertView *alertView = [YZMAlertView alertViewForRecommandWithContent:@"您还未实名认证，请先认证"];
            alertView.cancelButton.hidden = NO;
            [alertView.sureButton setTitle:@"立即验证" forState:UIControlStateNormal];
            alertView.cancleHandle = ^{
                
                [YZMHCMInstance popViewController:nil animated:YES];
            };
            alertView.confirmHandle  = ^{
                [YZMHCMInstance pushViewControllerWithName:@"identifyVerify" andParams:nil];
                return YES;
            };
            [alertView showInView:self.navigationController.view];
            
            return;
        }
        
        if ([_balanceValueLabel.text floatValue] == 0) {
            [MBProgressHUD showMessage:@"账户余额为0，不能进行提现！"];
            return;
        }

        NSArray *list = YZMUserServiceInstance.user.bankCardList;
        if ([list count] == 0 || list == nil) {
            YZMAlertView *view = [YZMAlertView alertViewForRecommandWithContent:@"还未绑定银行卡"];
            [view.sureButton setTitle:@"去绑定" forState:UIControlStateNormal];
            view.confirmHandle = ^(){
                [YZMHCMInstance pushViewControllerWithName:@"addBankCard" andParams:@{@"pageName":@"draw"}];
                return YES;
            };
            
            view.cancelButton.hidden = NO;
            view.cancleHandle = ^(){
                
            };
            [view showInView:self.navigationController.view];
            return;
        }
        //检测提现密码是否设置
        if (!YZMUserServiceInstance.user.detail.isWithDrawPw) {
            
            YZMAlertView *view = [YZMAlertView alertViewForRecommandWithContent:@"还未设置提现密码"];
            [view.sureButton setTitle:@"设定" forState:UIControlStateNormal];
            __weak __typeof(&*view) weakView = view;
            view.confirmHandle = ^(){
                
                [YZMHCMInstance pushViewControllerWithName:@"setWdPwd" andParams:nil];
                return YES;
            };
            
            view.cancelButton.hidden = NO;
            view.cancleHandle = ^(){
                
                [weakView dismissWithAnimationFlag:NO];
                [YZMHCMInstance popViewController];
            };
            [view showInView:self.navigationController.view];
            return;
        }

        [YZMDelayCharge showDelayChargeViewWithConfirmHandle:^BOOL{
            [YZMHCMInstance pushViewControllerWithName:@"draw" andParams:nil];
            return YES;
        } cancleHandle:nil noWaitPayHandle:^{
            [YZMHCMInstance pushViewControllerWithName:@"draw" andParams:nil];
        }];
       
    }
}


#pragma mark -- TableViewDataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_dataArray[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YZMSeparatorCell *cell = [tableView dequeueReusableCellWithIdentifier:@"identifier"];
    
    if (!cell) {
        
        cell = [[YZMSeparatorCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"identifier"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    cell.leftMargin = 10.0;
    cell.rightMargin = 10.0;
    YZMIndexCount indexCount;
    indexCount.index = indexPath.row;
    indexCount.count = [self.dataArray[indexPath.section] count];
    cell.indexCount = indexCount;
    
    cell.textLabel.textColor=[YZMAppStyle colorForMainTextColor];
    cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    

    cell.textLabel.text = [self.dataArray[indexPath.section][indexPath.row] objectForKey:@"titleName"];
    cell.textLabel.font = [YZMAppStyle mediumSizeFont];
    cell.imageView.image = [UIImage imageNamed:[self.dataArray[indexPath.section][indexPath.row] objectForKey:@"imageName"]];
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
    if (indexPath.section==1 && indexPath.row==2) {
        cell.detailTextLabel.textColor = [YZMAppStyle colorForIconColor];
        cell.detailTextLabel.font = [YZMAppStyle mediumSizeFont];
        cell.detailTextLabel.text=@"关注领红包";
    }
    
    [cell.contentView insertSubview:cell.textLabel belowSubview:cell.bottomLineView];

    
    return cell;
}

#pragma mark -- TableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return CELLHEIGHT;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return ControlSpacing15;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    return [[UIView alloc] init];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSString *pageName=[self.dataArray[indexPath.section][indexPath.row]objectForKey:YZNEXTPAGE];
    NSDictionary *params = nil;

    [YZMCMInstance pushByCheckingAuthWithName:pageName andParams:params];
}


#pragma mark -- Network Request

- (void)fetchUserInfo{
    
    [self fetchUserAssets];
    [YZMUserServiceInstance fetchUserDetailInfo];
    [YZMUserServiceInstance fetchUserBankCardInfo];
}

- (void)fetchUserAssets{
    
    [YZMUserServiceInstance fetchUserAssetsSuccess:^{
        
        if ([_refreshHeader isRefreshing]) {
            
            [_refreshHeader endRefreshing];
        }
        [self balanceRefresh];
        
    } failure:^(NSError *error) {
        
        if ([_refreshHeader isRefreshing]) {
            
            [_refreshHeader endRefreshing];
        }
        
        [error yz_showMessage];
    }];
}

- (void)dealloc
{
    _tableView.dataSource = nil;
    _tableView.delegate = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
